package com.hboxs.asl.util;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class BankUtils {


    /**
     * 暂时使用阿里巴巴的银行卡验证接口
     * @param cardNo
     * @return
     */
    public static String validateAndCacheCardInfo(String cardNo) {
        String httpUrl = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json";
        String httpArg = "_input_charset=utf-8&cardNo="+cardNo+"&cardBinCheck=true";
        String jsonResult = request(httpUrl, httpArg);
        JSONObject bankObject = new JSONObject(jsonResult);
        if(bankObject.isNull("bank")) return null;
        String bankCode = bankObject.getString("bank");
        return bankCode;
    }

    /**
     * 0@param
     * <p>
     * :请求接口
     *
     * @param httpArg :参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        validateAndCacheCardInfo("4581230715983369");
    }


}
